//
//  WTMainCategoryService.m
//  WTLiveSDKDemo
//
//  Created by ben on 16/10/7.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTMainCategoryService.h"
#import "WTCategoryModel.h"

static NSString*  Cache_Key_WXMainCategoryService = @"Cache_Key_WXMainCategoryService";

@implementation WTMainCategoryService

- (void)start:(NSDictionary *)param completionHandler:(WTServiceCompletionHandler)completionHandler{
    
    self.subPath = @"/live/pre";
    self.param = param;
    
    id  cache = [[WTCacheManager shareManager] objectForKey:Cache_Key_WXMainCategoryService];
    if(cache){
        NSArray* categories = [WTCategoryModel mj_objectArrayWithKeyValuesArray:cache];
        completionHandler(categories,nil);
    }

    [HYBNetworking postWithUrl:self.subPath refreshCache:YES params:@{@"hash":[self encode]} success:^(id response) {
        
        NSInteger code = [response[@"code"] integerValue];
        if(code == 200){
            NSArray* categories = [WTCategoryModel mj_objectArrayWithKeyValuesArray:response[@"hash"]];
            completionHandler(categories,nil);
            if(categories.count > 0){
                [[WTCacheManager shareManager] save:response[@"hash"] key:Cache_Key_WXMainCategoryService];
            }
        }else {
            completionHandler(@(NO),nil);
        }
        
    } fail:^(NSError *error) {
        id  cache = [[WTCacheManager shareManager] objectForKey:Cache_Key_WXMainCategoryService];
        if(cache){
            NSArray* categories = [WTCategoryModel mj_objectArrayWithKeyValuesArray:cache];
            completionHandler(categories,nil);
        }else {
            completionHandler(nil,nil);
        }
    }];
}
@end
